package com.muqiuhan.osmanthus.repository

import com.muqiuhan.osmanthus.config.Config
import com.muqiuhan.osmanthus.models.*
import scala.jdk.CollectionConverters.*
import com.muqiuhan.osmanthus.serializer.{AnyRefSerializer, JDKSerializationSerializer}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.jdbc.core.{BeanPropertyRowMapper, JdbcTemplate}

class TaskRepository:

  @Autowired
  @Qualifier("osmanthusJDBCTemplate")
  private val JDBCTemplate: JdbcTemplate = null;

  @Autowired
  private val config: Config = null

  private val serializer: AnyRefSerializer[?] =
    JDKSerializationSerializer[_root_.com.muqiuhan.osmanthus.models.Invocation]()

  def listNotStartedTasks(duration: Int): List[Task] =
    val query = """
      |SELECT
      |  id,node_id AS nodeId,pid,`name`,
      |  cron_expr AS cronExpr,STATUS,
      |  fail_count AS failCount,
      |  success_count AS successCount,
      |  VERSION,first_start_time AS firstStartTime,
      |  next_start_time AS nextStartTime,
      |  update_time AS updateTime,
      |  create_time AS createTime
      |FROM osmanthus
      |WHERE pid IS NULL AND next_start_time < date_sub(now(), interval ? second) AND STATUS = 0
      |ORDER BY next_start_time""".stripMargin
    JDBCTemplate.query(query, Array(duration.asInstanceOf[AnyRef]), new BeanPropertyRowMapper[Task](classOf[Task]))
      .asScala
      .toList
  end listNotStartedTasks

end TaskRepository
